package com.chat.server;

import com.chat.data.MySqlSingle;
import com.chat.entity.DataPackage;
import com.chat.entity.Message;
import com.chat.entity.Room;
import com.chat.mapper.MessageMapper;
import com.chat.mapper.RoomMapper;
import com.chat.mapper.UserMapper;
import com.chat.util.JwtUtils;
import io.netty.channel.ChannelHandlerContext;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息服务
 */
public class MessageServer implements DataPackagerServer{
    MessageMapper messageMapper;
    RoomMapper roomMapper;
    SqlSession sqlSession;

    public MessageServer() throws IOException {
        sqlSession = MySqlSingle.getMySqlSingle().getSqlSessionFactory().openSession();
        messageMapper = MySqlSingle.getMySqlSingle().getSqlSessionFactory().getConfiguration().getMapper(MessageMapper.class,sqlSession);
        roomMapper = MySqlSingle.getMySqlSingle().getSqlSessionFactory().getConfiguration().getMapper(RoomMapper.class,sqlSession);
    }

    @Override
    public DataPackage run(DataPackage source) {
        Map<String,Integer> param;
        switch (source.getAction()){
            case SEND_MESSAGE_FROM_ROOM:
                Message message = (Message) source.getDate();

                //
//                Room room = parent.getRoomMap().get(message.getRoomId());
//                room.updateMessage(message);
                messageMapper.insertMessage(message);
                sqlSession.commit();
                return DataPackage.successResponse("消息发送成功");

            case GET_MESSAGE_FROM_ROOM:
                String account = JwtUtils.getAccount(source.getToken());
                param = (Map<String, Integer>) source.getDate();
                List<Message> messages = messageMapper.selectMessageByRoom(param.get("roomId"));

//                //检测room
//                //如果用户不在连接池就更新
//                room = parent.getRoomMap().get(param.get("roomId"));
//                if(room != null){
//                    room = roomMapper.selectRoomById(param.get("roomId"));
//                }
//                if(room.getUserChannels().get(account)==null){
//                    room.getUserChannels().put(account,context);
//                }
                return DataPackage.successResponse(messages);
        }
        return  DataPackage.failResponse(null);
    }
}
